<template>
  <div>
    <!-- 面包屑导航   -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 搜索与添加区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">  
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户表 -->
      <el-table :data="userList" border stripe style="margin-top: 15px; font-size:12px;">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- 作用域插槽 slot-scope接受了当前作用域的数据 用scope-row接受当前行的数据-->
            <!-- {{ scope.row }}  -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>       
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- {{ scope }} -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getUserInfo(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(scope.row)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="giveInfo(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top:15px;">
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 主体区域 -->
      <el-form :model="addDialogForm" :rules="addFormRules" ref="addDialogFormRef" label-width="70px" class="demo-addDialogForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addDialogForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addDialogForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addDialogForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addDialogForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 主体区域 -->
      <el-form :model="editDialogForm" :rules="editFormRules" ref="editDialogFormRef" label-width="70px" class="demo-editDialogForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editDialogForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editDialogForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editDialogForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="giveDialogVisible" width="50%" @close="giveDialogClosed">
      <p>当前的用户: {{ roleInfo.username }}</p>
      <p>当前的角色: {{ roleInfo.role_name }}</p>
      <span>分配新角色: </span>
      <!-- 下拉菜单 -->
      <el-dropdown @command="roleCommand">
        <el-button type="primary">
          {{ MenuTitle }}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="roleItem in roleList" :key="roleItem.id" :command="roleItem">{{ roleItem.roleName }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <span slot="footer" class="dialog-footer">
        <el-button @click="giveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="giveUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 自定义邮箱验证规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if(regEmail.test(value)){
        return callback()
      }
      callback(new Error("请输入合法的邮箱"))
    }
    // 自定义手机号码验证规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if(regMobile.test(value)){
        return callback()
      }
      callback(new Error("请输入合法的手机号码"))
    }
    return {
      //  获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5
      },
      userList: [],
      roleList: [],
      MenuTitle: '角色菜单',
      newRoleId: '',
      total: 0,
      // 控制添加用户对话框的显示和隐藏
      addDialogVisible: false,
      editDialogVisible: false,
      giveDialogVisible: false,
      roleInfo: '',
      addDialogForm: {
        username: 'defalut',
        password: '111111',
        email: '11111@qq.com',
        mobile: '13278329911'
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 15, message: '用户名长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [ 
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogForm: {
        username: '',
        Email: '',
        Mobile: ''
      },
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 15, message: '用户名长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        email: [ 
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 获取当前点击修改的用户的id
      thisUserId: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    getUserList() {
      this.$http.get(
        'users', 
        { 
          params: this.queryInfo
        }).then(res => {
          // console.log(res.data)
          this.userList = res.data.data.users
          this.total = res.data.data.total
        })
    },
    // 监听 pagesize 改变事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 switch 开关状态的改变
    userStateChanged(userInfo) {
      // console.log(userInfo)
      // 调用接口保存用户状态
      this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`).then(res => {
        if(res.data.meta.status !== 200){
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error("更新状态失败")
        }else {
          this.$message.success("更新状态成功")
        }
      })
    },
    // 监听添加哦那个胡对话框的关闭事件
    addDialogClosed () {
      // 对话框关闭后重置整个表单并移除校验结果
      this.$refs.addDialogFormRef.resetFields()
    },
    // 点击对话框确定按钮添加新用户
    addUser() {
      this.$refs.addDialogFormRef.validate(valid => {
        // 接收校验结果
        console.log("预校验结果:" + valid)
        if(!valid){
          return 
        }else {
          // 预校验通过可以发送添加用户的请求
          this.$http.post('users', this.addDialogForm).then(res => {
            console.log(res.data)
            if(res.data.meta.status !== 201){
              this.$message.error("添加用户失败:" + res.data.meta.msg)
            }else{
              this.$message.success("添加用户" + this.addDialogForm.username + "成功")
              // 重新加载用户列表
              this.getUserList()
            }
          })
          // 关闭对话框
          this.addDialogVisible = false
        }
      })
    },
    // 
    editDialogClosed () {
      // 对话框关闭后重置整个表单并移除验证规则
      this.$refs.editDialogFormRef.resetFields()
    },
    // 拿到当前点击修改的用户的数据
    getUserInfo(scopeRow) {
      this.editDialogVisible = true
      // console.log(scopeRow)
      this.editDialogForm = {
        username: scopeRow.username,
        email: scopeRow.email,
        mobile: scopeRow.mobile
      }
      this.thisUserId = scopeRow.id
    },
    editUser() {
      this.$refs.editDialogFormRef.validate(valid => {
        console.log("预校验结果:" + valid)
        if(!valid){
          return
        }else {
          // 校验成功可以发送修改请求
          this.$http.put(`users/${this.thisUserId}`, {
            email: this.editDialogForm.email,
            mobile: this.editDialogForm.mobile
          }).then(res => {
            // console.log(res.data)
            if(res.data.meta.status !== 200){
              this.$message.error("修改数据失败:" + res.data.meta.msg)
            }else{
              this.$message.success("修改数据成功")
              this.thisUserId = ''
              this.getUserList()
            }
          })
        }
        this.editDialogVisible = false
      })
    },
    // 删除用户
    delUser(scopeRow) {
      this.$confirm("此操作将永久删除该用户,是否继续?", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$http.delete(`users/${scopeRow.id}`).then(res => {
          // console.log(res.data)
          if(res.data.meta.status !== 200){
            this.$message.error("删除失败:" + res.data.meta.msg)
          }else {
            this.$message.success("删除成功")
            this.getUserList()
          }
        })
      }).catch(() => {
        this.$message.info("已取消删除")
      });
    },
    // 打开对话框
    giveInfo(scopeRow) {
      this.giveDialogVisible = true
      // 更新当前打开的用户信息
      this.roleInfo = scopeRow
      // 获取角色列表
      this.$http.get('roles').then(res => {
        console.log(res.data)
        this.roleList = res.data.data
      })
      this.thisUserId = scopeRow.id
    },

    // 点击菜单菜单项，分配角色
    roleCommand(command) {
      this.MenuTitle = command.roleName
      this.newRoleId = command.id
    },

    // 关闭对话框
    giveDialogClosed() {
      this.MenuTitle = '角色菜单'
    },

    // 确认 发送请求
    giveUser() {
      // console.log(this.thisUserId)
      // console.log(this.newRoleId)
      if(!this.newRoleId) {
        return this.$message.error("请选择要分配的角色")
      }
      this.$http.put(`users/${this.thisUserId}/role`, {
        rid: this.newRoleId
      }).then(res => {
        if(res.data.meta.status !== 200) {
          this.$message.error(res.data.meta.msg)
        }else {
          this.$message.success(res.data.meta.msg)
          this.giveDialogVisible = false
          this.getUserList()
        }
      })
    }
  },
}
</script>
<style lang="scss" scoped>
  
</style>